import { PRIMARY_COLOR } from '@/common/constants/global'
import { useGlobalStore } from '@/stores/global'
import { transDarkColor, transLightColor } from '@/utils/color'
import { ElMessage } from 'element-plus'

export function useTheme() {
  const globalStore = useGlobalStore()

  /**
   * 初始化主题
   */
  const initTheme = () => {
    const theme = globalStore.theme
    changeTheme(theme)
  }

  /**
   * 切换主题
   */
  const toggleTheme = () => {
    const newTheme = globalStore.theme === 'dark' ? 'light' : 'dark'
    changeTheme(newTheme)
  }

  /**
   * 改变主题
   * @param {String} theme 主题
   */
  const changeTheme = (theme) => {
    globalStore.theme = theme
    // 获取当前的类列表
    const classList = document.documentElement.classList
    // 移除旧的主题类（'dark' 或 'light'）
    classList.remove('dark', 'light')
    // 添加新的主题类，同时保持其他类不变
    classList.add(theme)

    // 改变主题颜色
    const primaryColor = globalStore.primaryColor
    // 头部主题反转
    const isHeaderInverted = globalStore.isHeaderInverted
    // 侧边栏主题反转
    const isAsideInverted = globalStore.isAsideInverted
    // 全局圆角
    const borderRadius = globalStore.borderRadius

    changePrimaryColor(primaryColor)
    invertHeaderTheme(isHeaderInverted)
    invertAsideTheme(isAsideInverted)
    changeBorderRadius(borderRadius)
  }

  /**
   * 改变主题颜色
   * @param {String} color 主题颜色
   */
  const changePrimaryColor = (color) => {
    if (!color) {
      color = PRIMARY_COLOR
      ElMessage({ type: 'success', message: `主题颜色已重置为 ${PRIMARY_COLOR}` })
    }

    // 计算主题颜色变化
    document.documentElement.style.setProperty('--el-color-primary', color)

    for (let i = 1; i <= 9; i++) {
      const primaryLightColor = globalStore.theme == 'light' ? `${transLightColor(color, i / 10)}` : `${transDarkColor(color, i / 10)}`
      document.documentElement.style.setProperty(`--el-color-primary-light-${i}`, primaryLightColor)

      const primaryDarkColor = globalStore.theme == 'dark' ? `${transLightColor(color, i / 10)}` : `${transDarkColor(color, i / 10)}`
      document.documentElement.style.setProperty(`--el-color-primary-dark-${i}`, primaryDarkColor)
    }

    globalStore.primaryColor = color
  }

  /**
   * 改变头部主题
   * @param {Boolean} val 是否反转
   */
  const invertHeaderTheme = (val) => {
    globalStore.isHeaderInverted = val
    document.documentElement.classList.toggle('is-header-inverted', val)
  }

  /**
   * 改变侧边栏主题
   * @param {Boolean} val 是否反转
   */
  const invertAsideTheme = (val) => {
    globalStore.isAsideInverted = val
    document.documentElement.classList.toggle('is-aside-inverted', val)
  }

  /**
   * 改变侧边栏主题
   * @param {Boolean} val 是否反转
   */
  const changeBorderRadius = (val) => {
    globalStore.borderRadius = val
    document.documentElement.style.setProperty('--el-border-radius-base', val + 'px')
  }

  return {
    initTheme,
    changeTheme,
    toggleTheme,
    changePrimaryColor,
    invertHeaderTheme,
    invertAsideTheme,
    changeBorderRadius
  }
}
